	package gui.engraving;


	import javax.swing.JPanel;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import entities.Employee;
import entities.ProductionOrder;

import javax.swing.border.TitledBorder;

import java.awt.Color;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.miginfocom.swing.MigLayout;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.JButton;

import utilities.Services;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;
	
/**
 * @author Idan
 * List of reports GUI used before the seperation step.
 */
public class EngravingListOfReports extends JPanel
{
	private JTable table;
	private EngravingPanel myPanel;
	public DefaultTableModel model;
	private JButton deleteButton;
	public ArrayList<Object> listOfReports;
	private JButton exitButton;
	private JButton createSeperationReportButton;
	private JButton refreshButton;


		public EngravingListOfReports(EngravingPanel engravingPanel)
		{
			setBackground(new Color(173, 216, 230));
			this.myPanel=engravingPanel;
			setLayout(new FormLayout(new ColumnSpec[] {
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					ColumnSpec.decode("center:default:grow"),
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,},
				new RowSpec[] {
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					RowSpec.decode("default:grow"),
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,}));
			
			JPanel panel = new JPanel(){@Override
				public void paintComponent(Graphics g) {
		        Graphics2D g2d = (Graphics2D) g;
		        Color color1 = getBackground();
		        Color color2 = color1.darker();
		        int w = getWidth();
		        int h = getHeight(); 
		        GradientPaint gp = new GradientPaint(
		                0, 0, color1,
		                0, h, color2);

		        g2d.setPaint(gp);
		        g2d.fillRect(0, 0, w, h);
		        }};
			panel.setBackground(new Color(173, 216, 230));
			panel.setBorder(new TitledBorder(null, "\u05E8\u05E9\u05D9\u05DE\u05EA \u05D3\u05D5\u05D7\u05D5\u05EA \u05D9\u05D9\u05E6\u05D5\u05E8", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
			add(panel, "6, 4, center, fill");
			panel.setLayout(new MigLayout("", "[][600px:n,grow,center][]", "[300px:n,grow][29px]"));
			
			JScrollPane scrollPane = new JScrollPane();
			panel.add(scrollPane, "cell 1 0,grow");
			
			table = new JTable();
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0)
				{
					if (arg0.getClickCount() == 2)
					{
						// Double click
						createSeperationReport(table.getSelectedRow());
					}
				}
			});
			table.setFont(new Font("Tahoma", Font.PLAIN, 15));
			table.setBorder(new TitledBorder(null, "", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
			table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			scrollPane.setViewportView(table);
			table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
					"\u05E6\u05D3 2", "\u05E6\u05D3 1", "\u05E2\u05D5\u05D1\u05D3", "\u05EA\u05D0\u05E8\u05D9\u05DA", "\u05DB\u05DE\u05D5\u05EA", "\u05D3\u05D9\u05D5\u05E4\u05D8\u05E8", "\u05E1\u05D5\u05D2", "\u05E4\u05E7''\u05E2"
				}
			) {
				boolean[] columnEditables = new boolean[] {
					false, false, false, false, false, false, false, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			table.getColumnModel().getColumn(0).setResizable(false);
			table.getColumnModel().getColumn(0).setPreferredWidth(50);
			table.getColumnModel().getColumn(0).setMinWidth(50);
			table.getColumnModel().getColumn(1).setResizable(false);
			table.getColumnModel().getColumn(1).setPreferredWidth(50);
			table.getColumnModel().getColumn(1).setMinWidth(50);
			table.getColumnModel().getColumn(2).setResizable(false);
			table.getColumnModel().getColumn(2).setPreferredWidth(100);
			table.getColumnModel().getColumn(2).setMinWidth(100);
			table.getColumnModel().getColumn(3).setResizable(false);
			table.getColumnModel().getColumn(3).setPreferredWidth(100);
			table.getColumnModel().getColumn(3).setMinWidth(100);
			table.getColumnModel().getColumn(4).setResizable(false);
			table.getColumnModel().getColumn(4).setPreferredWidth(50);
			table.getColumnModel().getColumn(4).setMinWidth(50);
			table.getColumnModel().getColumn(5).setResizable(false);
			table.getColumnModel().getColumn(5).setPreferredWidth(50);
			table.getColumnModel().getColumn(5).setMinWidth(50);
			table.getColumnModel().getColumn(6).setResizable(false);
			table.getColumnModel().getColumn(6).setPreferredWidth(80);
			table.getColumnModel().getColumn(6).setMinWidth(80);
			table.getColumnModel().getColumn(7).setResizable(false);
			table.getColumnModel().getColumn(7).setPreferredWidth(110);
			table.getColumnModel().getColumn(7).setMinWidth(110);
			
			
			
			createSeperationReportButton = new JButton("יצירת דוח");
			createSeperationReportButton.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0)
				{
					
					int rowNumber = table.getSelectedRow();
            		if (rowNumber==-1)
            		{
            			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
            				    "יש לבחור ראשית פק''ע  מהרשימה.","שגיאה",JOptionPane.ERROR_MESSAGE);
            		}
            		else
            		{
	            		createSeperationReportButton.setEnabled(false);
	            		createSeperationReport(rowNumber);
	            		createSeperationReportButton.setEnabled(true);
            		}
				}
			});
			
			refreshButton = new JButton("רענן");
			refreshButton.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e)
				{
					refreshList();
				}
			});
			refreshButton.setIcon(new ImageIcon(EngravingListOfReports.class.getResource("/graphics/refreshOrders.png")));
			refreshButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
			panel.add(refreshButton, "flowx,cell 1 1");
			createSeperationReportButton.setIcon(new ImageIcon(EngravingListOfReports.class.getResource("/graphics/createReport.png")));
			createSeperationReportButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
			panel.add(createSeperationReportButton, "cell 1 1");
		
			
			
		
			this.model = (DefaultTableModel) table.getModel(); 
			
			exitButton = new JButton("יציאה");
			exitButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
			exitButton.setIcon(new ImageIcon(EngravingListOfReports.class.getResource("/graphics/exit.png")));
			exitButton.addMouseListener(new MouseAdapter() 
			{
				@Override
				public void mouseClicked(MouseEvent e)
				{
					Object[] options = {"כן","לא"};
	        		int n = JOptionPane.showOptionDialog(myPanel, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
	        		
	        		if (n==0)
	        		{
	        			if (myPanel.engravingClient != null)
	                    {
	                      try
	                      {
	                    	  myPanel.engravingClient.close();
	                      }
	                      catch (Exception ignore)
	                      {}
	                     }
	            		
	            		System.exit(0);
	        		}
				}
			});
			add(exitButton, "6, 6, center, center");
		} 



		

/**
 * Creates a seperation report
 */

		protected void createSeperationReport(int rowNumber)
		{
		
			String orderID = table.getValueAt(rowNumber, 7).toString();
			
			myPanel.seperatePanel.clearFields();
			myPanel.seperatePanel.orderIDTextField.setText(orderID);
			myPanel.seperatePanel.getOrderData(orderID);
			myPanel.setSelectedIndex(3);
			
		}





/**
 * Initializes the GUI
 */

		public void setVariables(ArrayList<Object> response)
		{
			listOfReports = (ArrayList<Object>) response.get(3);
	    	
	    	
	    	 
	        for (int i=1; i<=((int)listOfReports.get(0));i++)
	        {
	        	
	        	ProductionOrder report = (ProductionOrder)listOfReports.get(i);
	     
	            model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
	        }
	        
	    	
			
		}
		
	
/**
 * Removes an order report
 */
		private void deleteOrder(int rowNumber)
		{
	
			
			/**for reports already in the list - we have their engraveID - delete by it.
			* for reports made this run - need to get their engraveID
			*
			*after we remove the item from the table their indexes gets messed up
			*need to get the list of orders again to fix the indexes.
			*/
			
			// get engraveID for row
			int engraveID = ((ProductionOrder)listOfReports.get(rowNumber+1)).getEngraveID();
			
			
			ProductionOrder orderToDelete = new ProductionOrder();
			orderToDelete.setEngraveID(engraveID);
			orderToDelete.setOrderID( Integer.parseInt(table.getValueAt(rowNumber, 7).toString()) );
		//	orderToDelete.setOrderID(Integer.valueOf(value));
			ArrayList<Object> message = new ArrayList<Object>();
			ArrayList<Object> response = new ArrayList<Object>();
			
			message.add("deleteEngraveReport");
			message.add(orderToDelete);
			
			//ask for deletion
			try
			{
				response = myPanel.engravingClient.call(message);
				
				String reply = response.get(0).toString();
				if (reply.equalsIgnoreCase("Valid") )
				{
					// clear all table rows
					int rows = model.getRowCount(); 
					for(int j = rows - 1; j >=0; j--)
					{
					   model.removeRow(j); 
					}

					// initialize table with new list
					listOfReports = (ArrayList<Object>)response.get(1);
					 for (int i=1; i<=((int)listOfReports.get(0));i++)
				        {
				        	ProductionOrder report = (ProductionOrder)listOfReports.get(i);
				            model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
				            //Clear fields in the separate panel to prevent creating a report for an order after deleting it's report
				            myPanel.seperatePanel.clearFields();
				        }
					
				}
				else
				if (reply.equalsIgnoreCase("SQL Error") )
				{
					JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
        				    "ארעה שגיאה בבסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				else
				{
					JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
        				    "ארעה שגיאה בתקשורת לשרת.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
						
			} 
			catch (Exception e) 
			{
				
				//e.printStackTrace();
			}
			
			
		}






/**
 * Removes an order from the table.
 */
		public void removeFromTable(String orderID)
		{
			//System.out.println("Trying to remove orderID " + orderID + " from the list.");
			int reportsCounter = (int) listOfReports.get(0);
		//	System.out.println("There are " + reportsCounter + " reports in the list.");
			for (int index = (model.getRowCount()-1); index>=0; index-- )
			{
				//System.out.println("Index = " + index);
				if (Integer.parseInt(orderID) == ((ProductionOrder)listOfReports.get(index+1)).getOrderID() )
				{
					//System.out.println("Found a match for " + orderID + ", deleting it from the list.");
					listOfReports.remove(index+1);
					reportsCounter--;
					//model.removeRow(index);
				}
				// clear table row
				model.removeRow(index);
				//System.out.println("Removed row number " + index + " From the table");
			}
					
			
			listOfReports.set(0,reportsCounter);

			 for (int i=1; i<=((int)listOfReports.get(0));i++)
		        {
		        	
		        	ProductionOrder report = (ProductionOrder)listOfReports.get(i);
		        	//System.out.println("Iteration " + i + "Adding to the table " + report.getEngraveID());
		            model.addRow(new Object[]{report.getReportSideB(),report.getReportSideA(),report.getEmployee(),report.getEngraveDateAsString(),report.getQuantity(),report.getDiopter(),report.getType(),report.getOrderID()});
		        }
		}
		
			 /**
			  * Refresh the table
			  */
			 
			 protected void refreshList() 
				{
				
					
					// clear table
					// clear the table
					for (int row=model.getRowCount()-1 ; row>=0;row--)
						model.removeRow(row);
				
					// repopulate table
					
					 ArrayList<Object> message = new ArrayList<Object>();
				        message.add("initializeAllFieldsEngraving");
				         
				        try 
				        {
				   
				        	ArrayList<Object> response = myPanel.engravingClient.call(message);
				        	setVariables(response);
		     
				        } catch (Exception ex)
				        {
				        	
				            Logger.getLogger(EngravingFrame.class.getName()).log(Level.SEVERE, null, ex);
				        }
				        
				        
				}
	
			 @Override
				public void paintComponent(Graphics g) {
		        Graphics2D g2d = (Graphics2D) g;
		        Color color1 = getBackground();
		        Color color2 = color1.darker();
		        int w = getWidth();
		        int h = getHeight(); 
		        GradientPaint gp = new GradientPaint(
		                0, 0, color1,
		                0, h, color2);

		        g2d.setPaint(gp);
		        g2d.fillRect(0, 0, w, h);
		        }
	
}
